<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: absolute;
            left: 0;
            top: 0;
        }
    </style>
</head>

<body>
    <div class="box"></div>
</body>

</html>
<script>
    //一.边界运动
    //原理：让物体往不同的方向进行运动，如果碰到了浏览器的边界，反弹回来，一直在可视区内显示。
    //判断是否碰到了边界

    const box = document.querySelector('.box');
    let timer = null;
    let speedx = 6; //水平的速度
    let speedy = 9; //垂直的速度
    box.onclick = function() {
        clearInterval(timer);
        timer = setInterval(() => {
            //判断是否碰到了边界
            let left = box.offsetLeft + speedx;
            let top = box.offsetTop + speedy;
            if (top >= document.documentElement.clientHeight - box.offsetHeight) {
                top = document.documentElement.clientHeight - box.offsetHeight
                speedy *= -1; //速度取反
            } else if (top <= 0) {
                top = 0;
                speedy *= -1; //速度取反
            }


            if (left >= document.documentElement.clientWidth - box.offsetWidth) {
                left = document.documentElement.clientWidth - box.offsetWidth
                speedx *= -1; //速度取反
            } else if (left <= 0) {
                left = 0;
                speedx *= -1; //速度取反
            }


            box.style.left = left + 'px';
            box.style.top = top + 'px';
        }, 1000 / 60);
    };
</script>